package xju.rjxy.shop.web.controller;

import com.alibaba.fastjson.JSON;
import xju.rjxy.shop.common.framework.simplemvc.RequestMapping;
import xju.rjxy.shop.common.utils.JSONUtil;
import xju.rjxy.shop.common.utils.Result;
import xju.rjxy.shop.model.domain.Review;
import xju.rjxy.shop.model.vo.ReviewVO;
import xju.rjxy.shop.service.IReviewService;
import xju.rjxy.shop.service.impl.ReviewServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

/**
 * 评论控制层
 */
@RequestMapping("/api/review")
public class ReviewController {
    private final IReviewService reviewService = new ReviewServiceImpl();

    @RequestMapping("/list.do")
    public void getReviewList(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] ReviewController.getReviewList - 开始获取评论列表");
        try {
            // TODO 条件查询列表
            System.out.println("[DEBUG] ReviewController.getReviewList - 调用reviewService.getReviewList()");
            List<ReviewVO> reviewList = reviewService.getReviewList();
            System.out.println("[DEBUG] ReviewController.getReviewList - 获取到评论列表，数量: " + (reviewList != null ? reviewList.size() : 0));
            JSONUtil.printByJSON(response, Result.success(reviewList));
            System.out.println("[DEBUG] ReviewController.getReviewList - 响应发送成功");
        } catch (Exception e) {
            System.err.println("[ERROR] ReviewController.getReviewList - 获取评论列表失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail("获取评论列表失败: " + e.getMessage()));
        }
    }
    
    @RequestMapping("/game.do")
    public void getReviewListByGameId(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] ReviewController.getReviewListByGameId - 开始根据游戏ID获取评论列表");
        try {
            String gameIdStr = request.getParameter("gameId");
            System.out.println("[DEBUG] ReviewController.getReviewListByGameId - 请求参数 gameId: " + gameIdStr);
            
            if (gameIdStr == null || gameIdStr.trim().isEmpty()) {
                System.err.println("[ERROR] ReviewController.getReviewListByGameId - 游戏ID不能为空");
                JSONUtil.printByJSON(response, Result.fail("游戏ID不能为空"));
                return;
            }
            
            Integer gameId = Integer.parseInt(gameIdStr);
            System.out.println("[DEBUG] ReviewController.getReviewListByGameId - 解析后的gameId: " + gameId);
            
            System.out.println("[DEBUG] ReviewController.getReviewListByGameId - 调用reviewService.getReviewListByGameId()");
            List<ReviewVO> reviewList = reviewService.getReviewListByGameId(gameId);
            System.out.println("[DEBUG] ReviewController.getReviewListByGameId - 获取到评论列表，数量: " + (reviewList != null ? reviewList.size() : 0));
            JSONUtil.printByJSON(response, Result.success(reviewList));
            System.out.println("[DEBUG] ReviewController.getReviewListByGameId - 响应发送成功");
            
        } catch (NumberFormatException e) {
            System.err.println("[ERROR] ReviewController.getReviewListByGameId - 游戏ID格式错误: " + e.getMessage());
            JSONUtil.printByJSON(response, Result.fail("游戏ID格式错误"));
        } catch (Exception e) {
            System.err.println("[ERROR] ReviewController.getReviewListByGameId - 根据游戏ID获取评论列表失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/user.do")
    public void getReviewListByUserId(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] ReviewController.getReviewListByUserId - 开始根据用户ID获取评论列表");
        try {
            String userIdStr = request.getParameter("userId");
            System.out.println("[DEBUG] ReviewController.getReviewListByUserId - 请求参数 userId: " + userIdStr);
            
            if (userIdStr == null || userIdStr.trim().isEmpty()) {
                System.err.println("[ERROR] ReviewController.getReviewListByUserId - 用户ID不能为空");
                JSONUtil.printByJSON(response, Result.fail("用户ID不能为空"));
                return;
            }
            
            Integer userId = Integer.parseInt(userIdStr);
            System.out.println("[DEBUG] ReviewController.getReviewListByUserId - 解析后的userId: " + userId);
            
            System.out.println("[DEBUG] ReviewController.getReviewListByUserId - 调用reviewService.getReviewListByUserId()");
            List<ReviewVO> reviewList = reviewService.getReviewListByUserId(userId);
            System.out.println("[DEBUG] ReviewController.getReviewListByUserId - 获取到评论列表，数量: " + (reviewList != null ? reviewList.size() : 0));
            JSONUtil.printByJSON(response, Result.success(reviewList));
            System.out.println("[DEBUG] ReviewController.getReviewListByUserId - 响应发送成功");
            
        } catch (NumberFormatException e) {
            System.err.println("[ERROR] ReviewController.getReviewListByUserId - 用户ID格式错误: " + e.getMessage());
            JSONUtil.printByJSON(response, Result.fail("用户ID格式错误"));
        } catch (Exception e) {
            System.err.println("[ERROR] ReviewController.getReviewListByUserId - 根据用户ID获取评论列表失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/add.do")
    public void addReview(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] ReviewController.addReview - 开始添加评论");
        try {
            // 读取请求体
            System.out.println("[DEBUG] ReviewController.addReview - 开始读取请求体");
            Review review = readRequestBody(request, Review.class);
            System.out.println("[DEBUG] ReviewController.addReview - 解析后的评论对象: " + review);
            
            System.out.println("[DEBUG] ReviewController.addReview - 调用reviewService.addReview()");
            boolean success = reviewService.addReview(review);
            System.out.println("[DEBUG] ReviewController.addReview - 添加评论结果: " + (success ? "成功" : "失败"));
            
            if (success) {
                JSONUtil.printByJSON(response, Result.success("评论添加成功"));
                System.out.println("[DEBUG] ReviewController.addReview - 响应发送成功");
            } else {
                System.err.println("[ERROR] ReviewController.addReview - 评论添加失败");
                JSONUtil.printByJSON(response, Result.fail("评论添加失败"));
            }
            
        } catch (Exception e) {
            System.err.println("[ERROR] ReviewController.addReview - 添加评论失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/update.do")
    public void updateReview(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] ReviewController.updateReview - 开始更新评论");
        try {
            // 读取请求体
            System.out.println("[DEBUG] ReviewController.updateReview - 开始读取请求体");
            Review review = readRequestBody(request, Review.class);
            System.out.println("[DEBUG] ReviewController.updateReview - 解析后的评论对象: " + review);
            
            System.out.println("[DEBUG] ReviewController.updateReview - 调用reviewService.updateReview()");
            boolean success = reviewService.updateReview(review);
            System.out.println("[DEBUG] ReviewController.updateReview - 更新评论结果: " + (success ? "成功" : "失败"));
            
            if (success) {
                JSONUtil.printByJSON(response, Result.success("评论更新成功"));
                System.out.println("[DEBUG] ReviewController.updateReview - 响应发送成功");
            } else {
                System.err.println("[ERROR] ReviewController.updateReview - 评论更新失败");
                JSONUtil.printByJSON(response, Result.fail("评论更新失败"));
            }
            
        } catch (Exception e) {
            System.err.println("[ERROR] ReviewController.updateReview - 更新评论失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/delete.do")
    public void deleteReview(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] ReviewController.deleteReview - 开始删除评论");
        try {
            String reviewIdStr = request.getParameter("reviewId");
            System.out.println("[DEBUG] ReviewController.deleteReview - 请求参数 reviewId: " + reviewIdStr);
            
            if (reviewIdStr == null || reviewIdStr.trim().isEmpty()) {
                System.err.println("[ERROR] ReviewController.deleteReview - 评论ID不能为空");
                JSONUtil.printByJSON(response, Result.fail("评论ID不能为空"));
                return;
            }
            
            Integer reviewId = Integer.parseInt(reviewIdStr);
            System.out.println("[DEBUG] ReviewController.deleteReview - 解析后的reviewId: " + reviewId);
            
            System.out.println("[DEBUG] ReviewController.deleteReview - 调用reviewService.deleteReview()");
            boolean success = reviewService.deleteReview(reviewId);
            System.out.println("[DEBUG] ReviewController.deleteReview - 删除评论结果: " + (success ? "成功" : "失败"));
            
            if (success) {
                JSONUtil.printByJSON(response, Result.success("评论删除成功"));
                System.out.println("[DEBUG] ReviewController.deleteReview - 响应发送成功");
            } else {
                System.err.println("[ERROR] ReviewController.deleteReview - 评论删除失败");
                JSONUtil.printByJSON(response, Result.fail("评论删除失败"));
            }
            
        } catch (NumberFormatException e) {
            System.err.println("[ERROR] ReviewController.deleteReview - 评论ID格式错误: " + e.getMessage());
            JSONUtil.printByJSON(response, Result.fail("评论ID格式错误"));
        } catch (Exception e) {
            System.err.println("[ERROR] ReviewController.deleteReview - 删除评论失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/rating.do")
    public void getAverageRating(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] ReviewController.getAverageRating - 开始获取平均评分");
        try {
            String gameIdStr = request.getParameter("gameId");
            System.out.println("[DEBUG] ReviewController.getAverageRating - 请求参数 gameId: " + gameIdStr);
            
            if (gameIdStr == null || gameIdStr.trim().isEmpty()) {
                System.err.println("[ERROR] ReviewController.getAverageRating - 游戏ID不能为空");
                JSONUtil.printByJSON(response, Result.fail("游戏ID不能为空"));
                return;
            }
            
            Integer gameId = Integer.parseInt(gameIdStr);
            System.out.println("[DEBUG] ReviewController.getAverageRating - 解析后的gameId: " + gameId);
            
            System.out.println("[DEBUG] ReviewController.getAverageRating - 调用reviewService.getAverageRatingByGameId()");
            Double averageRating = reviewService.getAverageRatingByGameId(gameId);
            System.out.println("[DEBUG] ReviewController.getAverageRating - 获取到平均评分: " + averageRating);
            JSONUtil.printByJSON(response, Result.success(averageRating));
            System.out.println("[DEBUG] ReviewController.getAverageRating - 响应发送成功");
            
        } catch (NumberFormatException e) {
            System.err.println("[ERROR] ReviewController.getAverageRating - 游戏ID格式错误: " + e.getMessage());
            JSONUtil.printByJSON(response, Result.fail("游戏ID格式错误"));
        } catch (Exception e) {
            System.err.println("[ERROR] ReviewController.getAverageRating - 获取平均评分失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    /**
     * 读取请求体并转换为指定类型
     */
    private <T> T readRequestBody(HttpServletRequest request, Class<T> clazz) throws IOException {
        System.out.println("[DEBUG] ReviewController.readRequestBody - 开始读取请求体");
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String requestBody = sb.toString();
        System.out.println("[DEBUG] ReviewController.readRequestBody - 请求体内容: " + requestBody);
        
        T result = JSON.parseObject(requestBody, clazz);
        System.out.println("[DEBUG] ReviewController.readRequestBody - 解析后的对象: " + result);
        return result;
    }
} 